<?php
    class FavoritesController extends AppController
    {
        var $name = 'Favorites';
        var $layout = 'ajaxmsg';
        var $components = array('RequestHandler','Auth');
        function beforeFilter()
        {
            $this->Auth->allow('add','remove');
           
        }
        
        function add($sid=null)
        {
            $user=$this->Auth->user();
             if(empty($user)){
                $this->flash('您还未登录不能进行此操作','-1',5);
                return;
             }
            if(empty($sid)  or !is_numeric($sid)){
                    $this -> flash('请正确选择要加入收藏夹的网址信息','-1',5);
                    return;
            }
            $fdata = array();
            $fdata['site_id'] = $sid;
            $fdata['user_id'] = $uid = $this->Auth->user('id');
            $favs=$this->Favorite->find('first',array('user_id' => $uid,'site_id' => $sid));
            if(!empty($favs)){
                $this->flash('该网址您的收藏夹中已经存在了','-1',5);
                return;
            }
            $this->Favorite->create();
            if($this->Favorite->save($fdata)){
                $this->flash('已成功加入您的网址收藏夹','-1',5);
                return;
            }else{
                $this->flash('出现错误,未能加入收藏夹','-1',5);
                return;
            }
        }
        
        function remove($sid)
        {
            $user=$this->Auth->user();
             if(empty($user)){
                $this->flash('您还未登录不能进行此操作','-1',5);
                return;
             }
             if(empty($sid)  or !is_numeric($sid)){
                $this -> flash('请正确选择要加入收藏夹的网址信息','-1',5);
                return;
            }
            $uid = $this ->Auth->user('id');
            if($this->Favorite->deleteAll(array('user_id' => $uid,'site_id' => $sid))){
                $this -> flash('已从收藏夹中删除该网址','-1',5);
                return;
            }else{
                $this -> flash('出现错误，未能删除','-1',5);
                return;
            }
        }
    }
?>